package com.example.linearlayoutdemo;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.linearlayoutdemo.network.auth.model.User;
import com.example.linearlayoutdemo.network.fun.viewmodel.UserlistViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private TextView pomptTitleView;
    private UserViewModel userViewModel;

    private RecyclerView mRecyclerView;
    private TextAdapter mAdapter;

    private SwipeRefreshLayout mSwipeRefresh;

//    private final MutableLiveData<List<String>> mListData = new MutableLiveData<>();
    private UserlistViewModel listViewModel;

    public HomeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 4. 从MainActivity获取ViewModel（核心：拿到共享数据）
        userViewModel = ((HomeActivity) getActivity()).getUserViewModel();
        pomptTitleView = view.findViewById(R.id.title);
        // 1. 初始化视图
        initView(view);

//        // 2. 获取 ViewModel 实例（与 Fragment 生命周期绑定，旋转屏幕不重建）
//        listViewModel = new ViewModelProvider(this).get(ListViewModel.class);
//
//        // 3. 观察数据变化：数据更新时自动刷新列表
//        observeData();
//
//        // 4. 首次加载数据（仅在数据为空时加载，避免重复请求）
//        if(listViewModel.getListData().getValue() == null) {
//            listViewModel.loadData();
//        }

        listViewModel = new ViewModelProvider(this).get(UserlistViewModel.class); // 获取 ViewModel
        observeUserListStatus(); // 观察 LiveData
        listViewModel.loadUserList(); // 触发请求
    }
    // 观察 LiveData 状态，更新 UI
    private void observeUserListStatus() {
        listViewModel.observeUserList().observe(getViewLifecycleOwner(), resource -> {
            if (resource == null) return;
            switch (resource.getStatus()) {
                case LOADING:
                    // 显示加载中
//                    Toast.makeText(getContext(), "加载中。。。" , Toast.LENGTH_SHORT).show();
//                    progressBar.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    // 显示列表数据
//                    progressBar.setVisibility(View.GONE);
                    mAdapter.setData(resource.getData().getData());
                    // 数据加载完成后，停止刷新动画
                    mSwipeRefresh.setRefreshing(false);
                    break;
                case ERROR:
                    // 显示错误信息
//                    progressBar.setVisibility(View.GONE);
//                    tvError.setText(resource.getMessage());
                    Toast.makeText(getContext(), resource.getMessage(), Toast.LENGTH_SHORT).show();
                    break;
            }
        });
    }
    private void initView(View view) {
        mSwipeRefresh = view.findViewById(R.id.swipe_refresh);
        // 初始化 RecyclerView
        mRecyclerView = view.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new TextAdapter(new ArrayList<>()); // 初始空数据
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new TextAdapter.OnItemClickListener(){
            @Override
            public void onItemClick(int position, User data) {
                // 点击后弹出Toast显示数据
                Toast.makeText(getContext(), "点击了：" + data.getEmail(), Toast.LENGTH_SHORT).show();
                // 也可以在这里实现跳转页面等逻辑
                // 例如：Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                // intent.putExtra("data", data);
                // startActivity(intent);
            }
        });
        // 1. 设置刷新动画颜色（可选，最多设置4种）
        mSwipeRefresh.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_green_light
        );

        // 2. 设置下拉刷新监听器
        mSwipeRefresh.setOnRefreshListener(() -> {
            // 触发刷新时执行的逻辑（如请求新数据）
            // 调用 ViewModel 加载新数据（在子线程中执行）
//            listViewModel.refreshData();
            listViewModel.loadUserList(); // 触发请求
        });
    }
    private void observeData() {
        // 2. 调用 observe() 观察数据变化
        // 第一个参数：生命周期所有者（Fragment 的视图生命周期，避免内存泄漏）
        // 第二个参数：数据变化的观察者
//        listViewModel.getListData().observe(getViewLifecycleOwner(), new Observer<List<String>>() {
//            @Override
//            public void onChanged(List<String> data) {
//                // 数据变化时的回调（仅在 Fragment 活跃时触发）
//                if (data != null) {
////                    mInfoTv.setText("当前数据量：" + data.size());
//                    // 此处可更新 RecyclerView列表（与之前的Adapter配合）
//                    mAdapter.setData(data);
//                    // 数据加载完成后，停止刷新动画
//                    mSwipeRefresh.setRefreshing(false);
//                }
//            }
//        });
    }
    @Override
    public void onResume() {
        super.onResume();
        pomptTitleView.setText("您选择的兴趣是：" + userViewModel.getUserInterest()+"，据此推荐内容如下。");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mRecyclerView.setAdapter(null); // 解除关联，避免内存泄漏
    }
}